#!/bin/bash

# GOST 隧道中转配置脚本
# 支持中转机、落地机配置，服务管理，自动安装升级等功能

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 打印彩色信息
info() { echo -e "${BLUE}[INFO]${NC} $1"; }
success() { echo -e "${GREEN}[SUCCESS]${NC} $1"; }
warning() { echo -e "${YELLOW}[WARNING]${NC} $1"; }
error() { echo -e "${RED}[ERROR]${NC} $1"; }

# 检查root权限
check_root() {
    if [[ $EUID -ne 0 ]]; then
        error "此脚本需要root权限运行"
        info "请使用: sudo $0"
        exit 1
    fi
}

# 检查网络连接
check_network() {
    info "检查网络连接..."
    
    if ping -c 1 -W 3 github.com &> /dev/null || ping -c 1 -W 3 8.8.8.8 &> /dev/null; then
        success "网络连接正常"
        return 0
    else
        warning "网络连接不稳定，可能会影响安装和升级"
        return 1
    fi
}

# 检查并安装系统依赖
check_dependencies() {
    info "检查系统依赖..."
    
    local missing_deps=()
    
    # 检查 curl
    if ! command -v curl &> /dev/null; then
        missing_deps+=("curl")
    fi
    
    # 检查 wget (备用下载工具)
    if ! command -v wget &> /dev/null; then
        missing_deps+=("wget")
    fi
    
    if [ ${#missing_deps[@]} -gt 0 ]; then
        warning "缺少必要的依赖: ${missing_deps[*]}"
        info "自动安装依赖..."
        install_dependencies "${missing_deps[@]}"
    else
        success "系统依赖检查完成"
    fi
}

# 安装系统依赖
install_dependencies() {
    local deps=("$@")
    info "开始安装系统依赖: ${deps[*]}"
    
    if command -v apt-get &> /dev/null; then
        # Debian/Ubuntu
        apt-get update -y
        apt-get install -y "${deps[@]}"
    elif command -v yum &> /dev/null; then
        # CentOS/RHEL
        yum install -y "${deps[@]}"
    elif command -v dnf &> /dev/null; then
        # Fedora
        dnf install -y "${deps[@]}"
    elif command -v apk &> /dev/null; then
        # Alpine
        apk add "${deps[@]}"
    else
        error "不支持的包管理器，请手动安装: ${deps[*]}"
        exit 1
    fi
    
    if [ $? -eq 0 ]; then
        success "系统依赖安装完成"
    else
        error "系统依赖安装失败"
        exit 1
    fi
}

# 检查GOST是否已安装
check_gost_installed() {
    if command -v gost &> /dev/null; then
        GOST_VERSION=$(gost -V 2>/dev/null | head -n1 || echo "未知版本")
        success "检测到 GOST 已安装: $GOST_VERSION"
        return 0
    else
        warning "未检测到 GOST 安装"
        return 1
    fi
}

# 获取当前GOST版本
get_current_gost_version() {
    if command -v gost &> /dev/null; then
        local version_output=$(gost -V 2>/dev/null | head -n1)
        # 提取版本号，兼容不同格式
        if [[ $version_output =~ v[0-9]+\.[0-9]+\.[0-9]+ ]]; then
            echo "${BASH_REMATCH[0]}"
        elif [[ $version_output =~ [0-9]+\.[0-9]+\.[0-9]+ ]]; then
            echo "v${BASH_REMATCH[0]}"
        else
            echo "未知版本"
        fi
    else
        echo "未安装"
    fi
}

# 安装GOST
install_gost() {
    info "开始安装 GOST..."
    
    # 检查下载工具
    local download_tool=""
    if command -v curl &> /dev/null; then
        download_tool="curl"
    elif command -v wget &> /dev/null; then
        download_tool="wget"
    else
        error "没有可用的下载工具 (curl 或 wget)"
        exit 1
    fi
    
    info "使用下载工具: $download_tool"
    
    if [ "$download_tool" = "curl" ]; then
        # 使用 curl 安装
        if curl -fsSL --connect-timeout 30 --retry 3 https://github.com/go-gost/gost/raw/master/install.sh | bash -s -- --install; then
            success "GOST 安装完成"
            # 验证安装
            if check_gost_installed; then
                return 0
            else
                error "GOST 安装后验证失败，请手动安装"
                exit 1
            fi
        else
            error "GOST 安装失败"
            exit 1
        fi
    else
        # 使用 wget 安装
        if wget -qO- --timeout=30 --tries=3 https://github.com/go-gost/gost/raw/master/install.sh | bash -s -- --install; then
            success "GOST 安装完成"
            # 验证安装
            if check_gost_installed; then
                return 0
            else
                error "GOST 安装后验证失败，请手动安装"
                exit 1
            fi
        else
            error "GOST 安装失败"
            exit 1
        fi
    fi
}

# 使用国内镜像升级
upgrade_with_mirror() {
    info "使用国内镜像升级 GOST..."
    
    # 停止所有GOST服务
    stop_all_gost_services
    
    # 备份当前GOST
    local gost_path=$(which gost)
    if [ -n "$gost_path" ]; then
        info "备份当前 GOST: $gost_path -> ${gost_path}.bak"
        cp "$gost_path" "${gost_path}.bak"
    fi
    
    # 使用国内镜像下载
    local download_url="https://ghproxy.com/https://github.com/go-gost/gost/releases/download/v3.2.5/gost-linux-amd64.tar.gz"
    local temp_dir="/tmp/gost-upgrade-$$"
    
    mkdir -p "$temp_dir"
    cd "$temp_dir"
    
    info "正在从镜像下载 GOST v3.2.5..."
    
    if command -v wget &> /dev/null; then
        if wget -q --timeout=30 --tries=3 "$download_url" -O gost.tar.gz; then
            success "下载完成"
        else
            error "下载失败"
            restore_backup_and_restart
            return 1
        fi
    elif command -v curl &> /dev/null; then
        if curl -fsSL --connect-timeout 30 --retry 3 "$download_url" -o gost.tar.gz; then
            success "下载完成"
        else
            error "下载失败"
            restore_backup_and_restart
            return 1
        fi
    else
        error "没有可用的下载工具"
        restore_backup_and_restart
        return 1
    fi
    
    # 解压和安装
    info "正在安装 GOST..."
    tar -xzf gost.tar.gz
    if [ $? -eq 0 ] && [ -f "gost" ]; then
        sudo cp gost "$gost_path"
        sudo chmod +x "$gost_path"
        success "GOST 安装完成"
        
        # 验证安装
        local new_version=$(get_current_gost_version)
        if [ "$new_version" != "未知版本" ] && [ "$new_version" != "未安装" ]; then
            success "成功升级到版本: $new_version"
            
            # 清理临时文件
            rm -rf "$temp_dir"
            
            # 删除备份
            if [ -f "${gost_path}.bak" ]; then
                rm -f "${gost_path}.bak"
            fi
            
            # 重启服务
            restart_all_gost_services
            return 0
        else
            error "版本验证失败"
            restore_backup_and_restart
            return 1
        fi
    else
        error "解压或安装失败"
        restore_backup_and_restart
        return 1
    fi
}

# 恢复备份并重启服务
restore_backup_and_restart() {
    local gost_path=$(which gost)
    if [ -f "${gost_path}.bak" ]; then
        warning "恢复备份的 GOST..."
        sudo cp "${gost_path}.bak" "$gost_path"
        sudo chmod +x "$gost_path"
    fi
    restart_all_gost_services
}

# 智能升级GOST
smart_upgrade_gost() {
    info "开始升级 GOST..."
    
    local current_version=$(get_current_gost_version)
    info "当前版本: $current_version"
    
    # 尝试自动升级
    info "尝试自动升级到最新稳定版..."
    
    # 停止所有GOST服务
    stop_all_gost_services
    
    # 备份当前GOST二进制文件
    local gost_path=$(which gost)
    if [ -n "$gost_path" ]; then
        info "备份当前 GOST: $gost_path -> ${gost_path}.bak"
        cp "$gost_path" "${gost_path}.bak"
    fi
    
    # 使用官方安装脚本升级到最新稳定版
    info "正在下载并安装最新版本..."
    if bash <(curl -fsSL --connect-timeout 30 --retry 3 https://github.com/go-gost/gost/raw/master/install.sh) --install; then
        success "GOST 升级完成"
        
        # 验证新版本
        local new_version=$(get_current_gost_version)
        if [ "$new_version" != "未知版本" ] && [ "$new_version" != "未安装" ]; then
            success "成功升级到版本: $new_version"
            
            # 删除备份文件
            if [ -f "${gost_path}.bak" ]; then
                rm -f "${gost_path}.bak"
            fi
            
            # 重启GOST服务
            restart_all_gost_services
            return 0
        else
            error "版本验证失败，当前版本: $new_version"
            restore_backup_and_restart
            return 1
        fi
    else
        error "自动升级失败，尝试使用国内镜像..."
        restore_backup_and_restart
        upgrade_with_mirror
        return $?
    fi
}

# 停止所有GOST服务
stop_all_gost_services() {
    info "停止所有 GOST 服务..."
    
    local gost_services=$(systemctl list-units --all --type=service | grep gost | awk '{print $1}')
    
    if [ -n "$gost_services" ]; then
        for service in $gost_services; do
            if systemctl is-active --quiet "$service" 2>/dev/null; then
                info "停止服务: $service"
                systemctl stop "$service"
            fi
        done
        sleep 2
    fi
    
    # 停止所有GOST进程
    local gost_pids=$(pgrep -f gost 2>/dev/null || true)
    if [ -n "$gost_pids" ]; then
        info "停止 GOST 进程: $gost_pids"
        kill $gost_pids 2>/dev/null || true
        sleep 1
    fi
}

# 重启所有GOST服务
restart_all_gost_services() {
    info "重启所有 GOST 服务..."
    
    local gost_services=$(systemctl list-units --all --type=service | grep gost | awk '{print $1}')
    
    if [ -n "$gost_services" ]; then
        for service in $gost_services; do
            info "重启服务: $service"
            systemctl restart "$service" 2>/dev/null || true
        done
        success "所有 GOST 服务已重启"
    else
        info "没有找到 GOST 系统服务"
    fi
}

# 查看已存在的服务
show_existing_services() {
    echo
    info "正在检查已存在的 GOST 服务..."
    echo "="$(printf '%*s' 60 | tr ' ' '=')
    
    # 检查systemd服务
    local gost_services=$(systemctl list-units --all --type=service | grep gost | awk '{print $1}')
    
    if [ -n "$gost_services" ]; then
        success "发现的 Systemd 服务:"
        for service in $gost_services; do
            local status=$(systemctl is-active $service)
            local enabled=$(systemctl is-enabled $service 2>/dev/null || echo "unknown")
            echo "  🔹 $service - 状态: $status - 开机自启: $enabled"
            
            # 显示服务详细信息
            if [ "$status" = "active" ]; then
                local main_pid=$(systemctl show $service --property=MainPID | cut -d= -f2)
                if [ "$main_pid" -ne 0 ] 2>/dev/null; then
                    local cmdline=$(cat /proc/$main_pid/cmdline 2>/dev/null | tr '\0' ' ' || echo "N/A")
                    echo "     命令: $cmdline"
                fi
            fi
            echo
        done
    else
        echo "  📭 未找到 GOST 系统服务"
    fi
    
    # 检查运行中的GOST进程
    info "运行中的 GOST 进程:"
    local gost_pids=$(pgrep -f gost 2>/dev/null || true)
    
    if [ -n "$gost_pids" ]; then
        for pid in $gost_pids; do
            if [ -d "/proc/$pid" ]; then
                local cmdline=$(cat /proc/$pid/cmdline 2>/dev/null | tr '\0' ' ' || echo "N/A")
                local user=$(ps -o user= -p $pid 2>/dev/null || echo "N/A")
                echo "  🔹 PID: $pid - 用户: $user"
                echo "     命令: $cmdline"
                echo
            fi
        done
    else
        echo "  📭 未找到运行中的 GOST 进程"
        echo
    fi
    
    # 检查监听端口
    info "GOST 相关监听端口:"
    local listening_ports=$(ss -tlnp 2>/dev/null | grep gost || \
                           netstat -tlnp 2>/dev/null | grep gost)
    
    if [ -n "$listening_ports" ]; then
        echo "$listening_ports" | while read line; do
            echo "  🔹 $line"
        done
    else
        echo "  📭 未找到 GOST 监听端口"
    fi
    
    echo "="$(printf '%*s' 60 | tr ' ' '=')
}

# 显示服务详情
show_service_detail() {
    local service_name=$1
    echo
    info "服务详情: $service_name"
    echo "-"$(printf '%*s' 50 | tr ' ' '-')
    
    # 显示服务状态
    systemctl status $service_name --no-pager -l
    
    # 显示最近日志
    echo
    info "最近日志:"
    journalctl -u $service_name --no-pager -n 10
}

# 显示服务日志
show_service_logs() {
    local service_name=$1
    echo
    info "实时日志: $service_name (Ctrl+C 退出)"
    echo "-"$(printf '%*s' 50 | tr ' ' '-')
    journalctl -u $service_name -f
}

# 停止指定服务
stop_service() {
    local service_name=$1
    info "正在停止服务: $service_name"
    
    if systemctl is-active --quiet $service_name 2>/dev/null; then
        systemctl stop $service_name
        sleep 2
        if systemctl is-active --quiet $service_name; then
            error "服务停止失败: $service_name"
            return 1
        else
            success "服务已停止: $service_name"
            return 0
        fi
    else
        warning "服务未运行: $service_name"
        return 0
    fi
}

# 重启指定服务
restart_service() {
    local service_name=$1
    info "正在重启服务: $service_name"
    
    if systemctl restart $service_name; then
        sleep 2
        if systemctl is-active --quiet $service_name; then
            success "服务重启成功: $service_name"
            return 0
        else
            error "服务重启后未运行: $service_name"
            return 1
        fi
    else
        error "服务重启失败: $service_name"
        return 1
    fi
}

# 删除转发服务
delete_forward_service() {
    local service_name=$1
    local service_file="/etc/systemd/system/${service_name}"
    
    echo
    warning "⚠️  即将删除转发服务: $service_name"
    echo
    info "服务文件: $service_file"
    
    # 显示服务当前状态
    if systemctl is-active --quiet $service_name 2>/dev/null; then
        local status="运行中"
    else
        local status="已停止"
    fi
    echo "当前状态: $status"
    
    # 显示服务命令
    local main_pid=$(systemctl show $service_name --property=MainPID | cut -d= -f2)
    if [ "$main_pid" -ne 0 ] 2>/dev/null; then
        local cmdline=$(cat /proc/$main_pid/cmdline 2>/dev/null | tr '\0' ' ' || echo "N/A")
        echo "执行命令: $cmdline"
    fi
    
    echo
    read -p "❓ 确定要删除这个转发服务吗? [y/N]: " confirm_delete
    if [[ ! $confirm_delete =~ ^[Yy]$ ]]; then
        info "取消删除服务"
        return 1
    fi
    
    info "开始删除服务: $service_name"
    
    # 停止服务
    if systemctl is-active --quiet $service_name 2>/dev/null; then
        info "停止服务..."
        systemctl stop $service_name
        sleep 2
    fi
    
    # 禁用服务
    if systemctl is-enabled --quiet $service_name 2>/dev/null; then
        info "禁用服务..."
        systemctl disable $service_name
    fi
    
    # 删除服务文件
    if [ -f "$service_file" ]; then
        info "删除服务文件..."
        rm -f "$service_file"
    else
        warning "服务文件不存在: $service_file"
    fi
    
    # 重新加载systemd
    info "重新加载systemd..."
    systemctl daemon-reload
    
    # 重置失败状态
    systemctl reset-failed $service_name 2>/dev/null || true
    
    # 验证删除
    if [ ! -f "$service_file" ] && ! systemctl list-units --all | grep -q "$service_name"; then
        success "✅ 转发服务删除成功: $service_name"
        
        # 检查是否还有相关进程在运行
        local related_pids=$(pgrep -f "$service_name" 2>/dev/null || true)
        if [ -n "$related_pids" ]; then
            warning "发现相关进程仍在运行，正在清理..."
            kill $related_pids 2>/dev/null || true
            sleep 1
        fi
        
        return 0
    else
        error "❌ 服务删除失败: $service_name"
        return 1
    fi
}

# 批量删除服务
batch_delete_services() {
    echo
    info "批量删除服务"
    echo "="$(printf '%*s' 50 | tr ' ' '=')
    
    local gost_services=$(systemctl list-units --all --type=service | grep gost | awk '{print $1}')
    
    if [ -z "$gost_services" ]; then
        echo "📭 没有找到 GOST 服务"
        return
    fi
    
    echo "请选择要删除的服务 (多选，用空格分隔):"
    select service in $gost_services "全选" "返回"; do
        case $service in
            "返回")
                return
                ;;
            "全选")
                echo
                warning "⚠️  即将删除所有 GOST 服务!"
                read -p "❓ 确定删除所有 GOST 服务吗? [y/N]: " confirm_all
                if [[ $confirm_all =~ ^[Yy]$ ]]; then
                    for svc in $gost_services; do
                        delete_forward_service $svc
                    done
                else
                    info "取消批量删除"
                fi
                break
                ;;
            *)
                if [ -n "$service" ]; then
                    selected_services=()
                    for i in $REPLY; do
                        if [ $i -le ${#gost_services[@]} ]; then
                            selected_services+=($(echo $gost_services | cut -d' ' -f$i))
                        fi
                    done
                    
                    if [ ${#selected_services[@]} -gt 0 ]; then
                        echo
                        info "选中的服务: ${selected_services[*]}"
                        read -p "❓ 确定删除这些服务吗? [y/N]: " confirm_multiple
                        if [[ $confirm_multiple =~ ^[Yy]$ ]]; then
                            for svc in "${selected_services[@]}"; do
                                delete_forward_service $svc
                            done
                        else
                            info "取消删除"
                        fi
                    fi
                fi
                break
                ;;
        esac
    done
}

# 管理现有服务
manage_existing_services() {
    echo
    info "服务管理选项"
    echo "="$(printf '%*s' 50 | tr ' ' '=')
    
    show_existing_services
    
    local gost_services=$(systemctl list-units --all --type=service | grep gost | awk '{print $1}')
    
    if [ -n "$gost_services" ]; then
        echo
        echo "请选择操作:"
        select operation in "管理单个服务" "批量删除服务" "升级GOST" "返回主菜单"; do
            case $operation in
                "管理单个服务")
                    echo
                    echo "请选择要管理的服务:"
                    select service in $gost_services "返回"; do
                        case $service in
                            "返回")
                                break
                                ;;
                            *)
                                if [ -n "$service" ]; then
                                    while true; do
                                        echo
                                        info "管理服务: $service"
                                        echo "1) 查看状态和日志"
                                        echo "2) 查看实时日志"
                                        echo "3) 停止服务"
                                        echo "4) 重启服务"
                                        echo "5) 禁用开机自启"
                                        echo "6) 启用开机自启"
                                        echo "7) 删除此服务"
                                        echo "8) 返回上级菜单"
                                        
                                        read -p "请选择操作 [1-8]: " action
                                        
                                        case $action in
                                            1)
                                                show_service_detail $service
                                                ;;
                                            2)
                                                show_service_logs $service
                                                ;;
                                            3)
                                                stop_service $service
                                                ;;
                                            4)
                                                restart_service $service
                                                ;;
                                            5)
                                                systemctl disable $service
                                                success "已禁用开机自启: $service"
                                                ;;
                                            6)
                                                systemctl enable $service
                                                success "已启用开机自启: $service"
                                                ;;
                                            7)
                                                delete_forward_service $service
                                                # 如果删除成功，退出当前管理循环
                                                if [ $? -eq 0 ]; then
                                                    break 2
                                                fi
                                                ;;
                                            8)
                                                break 2
                                                ;;
                                            *)
                                                error "无效选择"
                                                ;;
                                        esac
                                    done
                                fi
                                break
                                ;;
                        esac
                    done
                    ;;
                "批量删除服务")
                    batch_delete_services
                    ;;
                "升级GOST")
                    smart_upgrade_gost
                    ;;
                "返回主菜单")
                    return
                    ;;
            esac
            break
        done
    else
        echo
        echo "📭 没有找到 GOST 服务"
        read -p "按回车键返回主菜单..."
    fi
}

# 配置中转机
configure_relay_server() {
    echo
    info "配置中转机"
    echo "="$(printf '%*s' 40 | tr ' ' '=')
    
    # 选择中转模式
    echo "请选择中转模式:"
    echo "1) 模式1 - 透明转发 (推荐)"
    echo "2) 模式2 - 指定目标转发"
    read -p "请选择 [1-2] (默认: 1): " MODE_CHOICE
    MODE_CHOICE=${MODE_CHOICE:-1}
    
    if [ "$MODE_CHOICE" = "1" ]; then
        # 模式1 - 透明转发
        echo
        info "模式1 - 透明转发配置"
        echo "-"$(printf '%*s' 30 | tr ' ' '-')
        
        # 本地监听端口
        while true; do
            read -p "请输入本地监听端口 (默认: 23001): " LOCAL_PORT
            LOCAL_PORT=${LOCAL_PORT:-23001}
            
            if [[ $LOCAL_PORT =~ ^[0-9]+$ ]] && [ $LOCAL_PORT -gt 0 ] && [ $LOCAL_PORT -le 65535 ]; then
                if ss -tln | grep -q ":$LOCAL_PORT "; then
                    warning "端口 $LOCAL_PORT 已被占用，请选择其他端口"
                else
                    break
                fi
            else
                error "端口号必须是 1-65535 之间的数字"
            fi
        done
        
        # 中转端口
        while true; do
            read -p "请输入中转端口 (默认: 24001): " RELAY_PORT
            RELAY_PORT=${RELAY_PORT:-24001}
            
            if [[ $RELAY_PORT =~ ^[0-9]+$ ]] && [ $RELAY_PORT -gt 0 ] && [ $RELAY_PORT -le 65535 ]; then
                break
            else
                error "端口号必须是 1-65535 之间的数字"
            fi
        done
        
        # 落地机地址
        read -p "请输入落地机地址 (IP或域名): " TARGET_SERVER
        if [ -z "$TARGET_SERVER" ]; then
            error "落地机地址不能为空"
            exit 1
        fi
        
        START_CMD="gost -L tcp://:${LOCAL_PORT} -F relay+tls://${TARGET_SERVER}:${RELAY_PORT}"
        SERVICE_NAME="gost-relay-${LOCAL_PORT}"
        CONFIG_DESC="中转机 - 透明转发 (本地:${LOCAL_PORT} -> ${TARGET_SERVER}:${RELAY_PORT})"
        
    else
        # 模式2 - 指定目标转发
        echo
        info "模式2 - 指定目标转发配置"
        echo "-"$(printf '%*s' 30 | tr ' ' '-')
        
        # 本地监听端口
        while true; do
            read -p "请输入本地监听端口 (默认: 23001): " LOCAL_PORT
            LOCAL_PORT=${LOCAL_PORT:-23001}
            
            if [[ $LOCAL_PORT =~ ^[0-9]+$ ]] && [ $LOCAL_PORT -gt 0 ] && [ $LOCAL_PORT -le 65535 ]; then
                if ss -tln | grep -q ":$LOCAL_PORT "; then
                    warning "端口 $LOCAL_PORT 已被占用，请选择其他端口"
                else
                    break
                fi
            else
                error "端口号必须是 1-65535 之间的数字"
            fi
        done
        
        # 中转端口
        while true; do
            read -p "请输入中转端口 (默认: 24001): " RELAY_PORT
            RELAY_PORT=${RELAY_PORT:-24001}
            
            if [[ $RELAY_PORT =~ ^[0-9]+$ ]] && [ $RELAY_PORT -gt 0 ] && [ $RELAY_PORT -le 65535 ]; then
                break
            else
                error "端口号必须是 1-65535 之间的数字"
            fi
        done
        
        # 落地机地址
        read -p "请输入落地机地址 (IP或域名): " TARGET_SERVER
        if [ -z "$TARGET_SERVER" ]; then
            error "落地机地址不能为空"
            exit 1
        fi
        
        # 最终目标
        read -p "请输入最终目标地址 (格式: IP:端口, 例如: 192.168.1.100:80): " FINAL_TARGET
        if [ -z "$FINAL_TARGET" ]; then
            error "最终目标地址不能为空"
            exit 1
        fi
        
        START_CMD="gost -L tcp://:${LOCAL_PORT}/${FINAL_TARGET} -F relay+tls://${TARGET_SERVER}:${RELAY_PORT}"
        SERVICE_NAME="gost-relay-${LOCAL_PORT}"
        CONFIG_DESC="中转机 - 指定目标 (本地:${LOCAL_PORT} -> ${TARGET_SERVER}:${RELAY_PORT} -> ${FINAL_TARGET})"
    fi
}

# 配置落地机
configure_target_server() {
    echo
    info "配置落地机"
    echo "="$(printf '%*s' 40 | tr ' ' '=')
    
    # 选择落地机模式
    echo "请选择落地机模式:"
    echo "1) 模式1 - 透明代理 (推荐)"
    echo "2) 模式2 - 纯中转"
    read -p "请选择 [1-2] (默认: 1): " TARGET_MODE
    TARGET_MODE=${TARGET_MODE:-1}
    
    if [ "$TARGET_MODE" = "1" ]; then
        # 模式1 - 透明代理
        echo
        info "模式1 - 透明代理配置"
        echo "-"$(printf '%*s' 30 | tr ' ' '-')
        
        # 中转端口
        while true; do
            read -p "请输入中转端口 (默认: 24001): " RELAY_PORT
            RELAY_PORT=${RELAY_PORT:-24001}
            
            if [[ $RELAY_PORT =~ ^[0-9]+$ ]] && [ $RELAY_PORT -gt 0 ] && [ $RELAY_PORT -le 65535 ]; then
                if ss -tln | grep -q ":$RELAY_PORT "; then
                    warning "端口 $RELAY_PORT 已被占用，请选择其他端口"
                else
                    break
                fi
            else
                error "端口号必须是 1-65535 之间的数字"
            fi
        done
        
        # 落地机监听端口
        while true; do
            read -p "请输入落地机监听端口 (默认: 25001): " TARGET_PORT
            TARGET_PORT=${TARGET_PORT:-25001}
            
            if [[ $TARGET_PORT =~ ^[0-9]+$ ]] && [ $TARGET_PORT -gt 0 ] && [ $TARGET_PORT -le 65535 ]; then
                break
            else
                error "端口号必须是 1-65535 之间的数字"
            fi
        done
        
        START_CMD="gost -L relay+tls://:${RELAY_PORT}/:${TARGET_PORT}"
        SERVICE_NAME="gost-target-${RELAY_PORT}"
        CONFIG_DESC="落地机 - 透明代理 (中转:${RELAY_PORT} -> 本地:${TARGET_PORT})"
        
    else
        # 模式2 - 纯中转
        echo
        info "模式2 - 纯中转配置"
        echo "-"$(printf '%*s' 30 | tr ' ' '-')
        
        # 中转端口
        while true; do
            read -p "请输入中转端口 (默认: 24001): " RELAY_PORT
            RELAY_PORT=${RELAY_PORT:-24001}
            
            if [[ $RELAY_PORT =~ ^[0-9]+$ ]] && [ $RELAY_PORT -gt 0 ] && [ $RELAY_PORT -le 65535 ]; then
                if ss -tln | grep -q ":$RELAY_PORT "; then
                    warning "端口 $RELAY_PORT 已被占用，请选择其他端口"
                else
                    break
                fi
            else
                error "端口号必须是 1-65535 之间的数字"
            fi
        done
        
        START_CMD="gost -L relay+tls://:${RELAY_PORT}"
        SERVICE_NAME="gost-target-${RELAY_PORT}"
        CONFIG_DESC="落地机 - 纯中转 (中转端口:${RELAY_PORT})"
    fi
}

# 显示配置信息
show_config() {
    echo
    success "配置完成!"
    echo "="$(printf '%*s' 50 | tr ' ' '=')
    echo "角色: $CONFIG_DESC"
    echo "启动命令: $START_CMD"
    echo "服务名称: $SERVICE_NAME"
    echo "="$(printf '%*s' 50 | tr ' ' '=')
}

# 停止已存在的服务
stop_existing_service() {
    local service_name=$1
    if systemctl is-active --quiet $service_name 2>/dev/null; then
        warning "停止现有服务: $service_name"
        systemctl stop $service_name
        sleep 2
    fi
}

# 创建系统服务
create_system_service() {
    local service_name=$1
    local service_file="/etc/systemd/system/${service_name}.service"
    
    stop_existing_service $service_name
    
    info "创建系统服务: $service_name"
    
    # 创建服务文件
    cat > /tmp/${service_name}.service << EOF
[Unit]
Description=GOST Tunnel Service (${service_name})
After=network.target

[Service]
Type=simple
User=root
ExecStart=$(which gost) $(echo $START_CMD | sed 's/^gost //')
Restart=always
RestartSec=3
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target
EOF
    
    # 安装服务
    cp /tmp/${service_name}.service $service_file
    systemctl daemon-reload
    systemctl enable $service_name.service
    
    success "系统服务创建完成: $service_name"
}

# 配置防火墙
configure_firewall() {
    local port=$1
    
    info "配置防火墙..."
    
    if command -v ufw &> /dev/null && ufw status | grep -q "Status: active"; then
        ufw allow $port/tcp
        success "UFW 防火墙已开放端口 $port"
    fi
    
    if command -v firewall-cmd &> /dev/null && firewall-cmd --state &>/dev/null; then
        firewall-cmd --add-port=$port/tcp --permanent
        firewall-cmd --reload
        success "FirewallD 防火墙已开放端口 $port"
    fi
}

# 启动服务
start_service() {
    echo
    read -p "是否立即启动服务? [Y/n]: " START_NOW
    if [[ ! $START_NOW =~ ^[Nn]$ ]]; then
        info "启动 GOST 隧道服务..."
        
        # 创建系统服务
        create_system_service $SERVICE_NAME
        
        # 启动服务
        if systemctl start $SERVICE_NAME.service; then
            sleep 2
            if systemctl is-active --quiet $SERVICE_NAME.service; then
                success "GOST 隧道服务启动成功!"
                
                # 显示服务信息
                echo
                info "服务管理命令:"
                echo "查看状态: systemctl status $SERVICE_NAME.service"
                echo "查看日志: journalctl -u $SERVICE_NAME.service -f"
                echo "停止服务: systemctl stop $SERVICE_NAME.service"
                echo "重启服务: systemctl restart $SERVICE_NAME.service"
            else
                error "服务启动异常"
                systemctl status $SERVICE_NAME.service
            fi
        else
            error "服务启动失败"
        fi
        
        # 配置防火墙
        if [ "$ROLE" = "relay" ]; then
            configure_firewall $LOCAL_PORT
        else
            configure_firewall $RELAY_PORT
        fi
        
    else
        info "手动启动命令:"
        echo "nohup $START_CMD > gost.log 2>&1 &"
        echo
        info "或创建系统服务:"
        echo "systemctl enable $SERVICE_NAME.service"
        echo "systemctl start $SERVICE_NAME.service"
    fi
}

# 选择角色
select_role() {
    while true; do
        echo
        info "请选择操作:"
        echo "1) 中转机 (跳板服务器)"
        echo "2) 落地机 (目标服务器)"
        echo "3) 查看和管理现有服务"
        echo "4) 升级GOST"
        echo "5) 退出"
        read -p "请选择 [1-5]: " ROLE_CHOICE
        
        case $ROLE_CHOICE in
            1) 
                ROLE="relay"
                configure_relay_server
                break
                ;;
            2) 
                ROLE="target"
                configure_target_server
                break
                ;;
            3)
                manage_existing_services
                ;;
            4)
                smart_upgrade_gost
                ;;
            5)
                info "退出脚本"
                exit 0
                ;;
            *)
                error "无效选择，请重新输入"
                ;;
        esac
    done
}

# 主函数
main() {
    echo
    echo -e "${GREEN}=== GOST 隧道中转配置脚本 ===${NC}"
    echo
    
    # 检查root权限
    check_root
    
    # 检查网络连接
    check_network
    
    # 检查系统依赖（自动安装，无需确认）
    check_dependencies
    
    # 检查GOST安装（自动安装，无需确认）
    if ! check_gost_installed; then
        info "自动安装 GOST..."
        if install_gost; then
            success "GOST 安装成功"
        else
            warning "自动安装失败，请检查网络连接"
            exit 1
        fi
    fi
    
    # 选择角色和配置
    select_role
    
    # 如果是配置新服务，继续执行
    if [ -n "$ROLE" ]; then
        show_config
        start_service
        
        echo
        success "隧道中转配置完成!"
    fi
}

# 脚本入口
if [[ $1 == "-h" || $1 == "--help" ]]; then
    echo "用法: $0"
    echo "功能: GOST 隧道中转配置脚本"
    echo "特点:"
    echo "  - 自动安装系统依赖"
    echo "  - 自动安装GOST"
    echo "  - 智能升级GOST（支持网络故障处理）"
    echo "  - 支持中转机和落地机配置"
    echo "  - 两种中转模式可选"
    echo "  - 查看和管理现有服务"
    echo "  - 删除转发服务"
    echo "  - 批量删除服务"
    echo "  - 自动创建系统服务"
    echo "  - 自动配置防火墙"
    echo ""
    echo "命令行参数:"
    echo "  status/list    查看现有服务状态"
    echo "  delete <服务名> 删除指定服务"
    echo "  upgrade/update 升级GOST"
    exit 0
fi

if [[ $1 == "status" || $1 == "list" ]]; then
    show_existing_services
    exit 0
fi

if [[ $1 == "delete" && -n "$2" ]]; then
    delete_forward_service "$2"
    exit 0
fi

if [[ $1 == "upgrade" || $1 == "update" ]]; then
    smart_upgrade_gost
    exit 0
fi

main